package com.example.controller;

import com.example.common.RequirePermission;
import com.example.common.Result;
import com.example.dto.RoleMenuPermissionDTO;
import com.example.service.RolePermissionService;
import com.example.service.RoleMenuService;
import com.example.service.MenuManagementService;
import com.example.vo.MenuManagementVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 角色菜单管理控制器
 * 专门处理角色菜单分配，确保菜单权限绑定
 */
@RestController
@RequestMapping("/api/role-menu")
@CrossOrigin
public class RoleMenuController {

    @Autowired
    private RolePermissionService rolePermissionService;

    @Autowired
    private RoleMenuService roleMenuService;

    @Autowired
    private MenuManagementService menuManagementService;

    /**
     * 为角色分配菜单（自动绑定对应权限）
     */
    @PostMapping("/assign-with-permissions")
    @RequirePermission("admin:role:menu:assign")
    public Result<String> assignMenusWithPermissions(@RequestParam Long roleId, @RequestBody List<Long> menuIds) {
        return rolePermissionService.assignMenusWithPermissions(roleId, menuIds);
    }

    /**
     * 为角色分配菜单（不自动绑定权限）
     */
    @PostMapping("/assign")
    @RequirePermission("admin:role:menu:assign")
    public Result<String> assignMenusToRole(@RequestParam Long roleId, @RequestBody List<Long> menuIds) {
        return roleMenuService.assignMenusToRole(roleId, menuIds);
    }

    /**
     * 同时分配菜单和权限
     */
    @PostMapping("/assign-menu-permission")
    @RequirePermission("admin:role:menu:assign")
    public Result<String> assignMenuAndPermissions(@RequestBody RoleMenuPermissionDTO dto) {
        return rolePermissionService.assignMenuAndPermissions(dto);
    }

    /**
     * 获取所有菜单树（用于角色菜单分配）
     */
    @GetMapping("/menu-tree")
    @RequirePermission("admin:menu:list")
    public Result<List<MenuManagementVO>> getMenuTreeForAssignment() {
        return menuManagementService.getAllMenusTree();
    }

    /**
     * 获取角色已分配的菜单ID列表
     */
    @GetMapping("/role/{roleId}/menus")
    @RequirePermission("admin:role:menu:view")
    public Result<List<Long>> getRoleMenuIds(@PathVariable Long roleId) {
        return roleMenuService.getRoleMenuIds(roleId);
    }

    /**
     * 删除角色的所有菜单
     */
    @DeleteMapping("/role/{roleId}")
    @RequirePermission("admin:role:menu:delete")
    public Result<String> removeRoleMenus(@PathVariable Long roleId) {
        return roleMenuService.removeRoleMenus(roleId);
    }

    /**
     * 检查角色菜单权限一致性
     */
    @PostMapping("/check-consistency/{roleId}")
    @RequirePermission("admin:role:permission:manage")
    public Result<String> checkMenuPermissionConsistency(@PathVariable Long roleId) {
        return rolePermissionService.checkAndFixConsistency(roleId);
    }
}